#include <stdio.h>
#include <stdlib.h>
#include "dll.h"

struct node tail;
struct node head = {0, NULL, &tail};
struct node tail = {0, &head, NULL};

static link phead = &head;
static link ptail = &tail;

link new_node(item_t item)
{
    link p = malloc(sizeof *p);
    p->item = item;
    p->prev = p->next = NULL;
    return p;
}

void free_node(link p)
{
    free(p);
}

link search(item_t key)
{
    link p;
    for (p = phead->next; p != ptail; p = p->next)
        if (p->item == key)
            return p;
    return NULL;
}

void insert(link p)
{
    p->next = phead->next;
    phead->next->prev = p;
    phead->next = p;
    p->prev = phead;
}

void delete(link p)
{
    p->prev->next = p->next;
    p->next->prev = p->prev;
}

void traverse(void (*visit)(link))
{
    link p;
    for (p = phead->next; p != ptail; p = p->next)
        visit(p);
}

static unsigned int n = 0;
static void cnt_add(void)
{
    n += 1;
}

static void cnt_reset(void)
{
    n = 0;
}

static unsigned int cnt_read(void)
{
    return n;
}

static void cnt(link p)
{
    cnt_add();
}

#if 0
void reverse(void)
{
    cnt_reset();
    traverse(cnt);
    
    int n = cnt_read();
    printf("----n=%d--%s----\n", n, __FUNCTION__);
    if (n < 2) {
        fprintf(stderr, "few data in the list. nothing reverse.\n");
        return;
    }
    
    link pre, forward;
    pre = head;
    head = head->next;
    pre->next = NULL;
    forward = head->next;
    head->next = pre;
    
    for (; forward;) {
        pre = head;
        head = forward;
        forward = forward->next;
        head->next = pre;            
    }
}
#endif

void destroy(void)
{
    link q, p = phead->next;
    phead->next = ptail;
    ptail->prev = phead;
    while (p != ptail) {
        q = p;
        p = p->next;
        free_node(q);
    }
}

void enqueue(link p)
{
    insert(p);
}

link dequeue(void)
{
    if (ptail->prev == phead)
        return NULL;
    else {
        link p = ptail->prev;
        delete(p);
        return p;
    }
}


